#include "importdialog.h"
#include "ui_importdialog.h"
#include <QTimer>
#include <QProgressDialog>
#include <QMessageBox>

ImportDialog::ImportDialog(PioCore * core, ImportModule * module, QString source, QWidget *parent)
    : QDialog(parent),
      ui(new Ui::ImportDialog),
      m_core(core),
      m_module(module),
      m_currentThumbnailIndex(0)
{
    ui->setupUi(this);
    m_module->initialize(source);
    for(int i = 0; i < m_module->count(); i++)
        ui->lwItems->addItem(m_module->title(i));

    //ui->cbDeleteOriginals->setChecked(m_core->settings().value("ImportDialogDeleteAfterImport", false).toBool());
    ui->cbEject->setChecked(m_core->settings().value("ImportDialogEject", true).toBool());

    QTimer::singleShot(100, this, SLOT(loadNextThumbnail()));
}

ImportDialog::~ImportDialog()
{
    m_core->settings().setValue("ImportDialogDeleteAfterImport", ui->cbDeleteOriginals->isChecked());
    m_core->settings().setValue("ImportDialogEject", ui->cbEject->isChecked());
    delete ui;
}

void ImportDialog::loadNextThumbnail()
{
    if(m_currentThumbnailIndex >= m_module->count())
        return;

    QPixmap thumb = m_module->thumbnail(m_currentThumbnailIndex, ui->lwItems->iconSize());
    QListWidgetItem * item = ui->lwItems->item(m_currentThumbnailIndex);
    if(item != 0) {
        item->setIcon(thumb);
    }

    m_currentThumbnailIndex++;
    QTimer::singleShot(100, this, SLOT(loadNextThumbnail()));
}

void ImportDialog::on_buttonImport_pressed()
{
    QList<int> sel;
    QList<QListWidgetItem*> items = ui->lwItems->selectedItems();
    for(int i = 0; i < items.count(); i++) {        
        int row = ui->lwItems->row(items[i]);
        if(row >= 0 && row < m_module->count())
            sel << row;
    }

    emit import(m_module, sel, ui->cbDeleteOriginals->isChecked(), ui->cbEject->isChecked());
    close();
}

void ImportDialog::on_buttonCancel_pressed()
{
    close();
}
